import 'dart:math';

import 'package:auto_orientation/auto_orientation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';

class VideoWidgetView extends StatefulWidget {
  final List<String> urls;
  VideoWidgetView(
      {Key? key,
      this.urls = const [
        'https://workyd.com/image/car_light/shuai.mp4',
        'https://workyd.com/image/car_light/zhibao.mp4'
      ]})
      : super(key: key);

  @override
  State<VideoWidgetView> createState() => _VideoWidgetViewState();
}

class VideType {
  final String url;
  final double position;

  VideType(this.url, this.position);
}

class _VideoWidgetViewState extends State<VideoWidgetView> {
  VideoPlayerController? _controller;
  int currentIndex = 0;
  bool _isPlaying = false;
  bool _disposed = false;
  bool _noMute = false;
  late List<VideType> videos;
  bool _isFullScreen = true;

  @override
  void initState() {
    super.initState();
    videos = widget.urls.map((it) {
      return VideType(it, 0);
    }).toList();
    indexChange(0);
  }

  playEnd() {}
  var _onUpdateControllerTime;
  void conrtollerUpdate() async {
    if (_disposed) {
      return;
    }
    _onUpdateControllerTime = 0;
    final now = DateTime.now().millisecondsSinceEpoch;
    if (_onUpdateControllerTime > now) {
      return;
    }
    _onUpdateControllerTime = now + 500;
    final controller = _controller;
    if (controller == null) {
      print('controller不能为null');
      return;
    }
    if (!controller.value.isInitialized) {
      print('还没有初始化完成');
      return;
    }
    _duration ??= _controller?.value.duration;
    var duration = _duration;
    if (duration == null) return;

    var position = await _controller?.position;
    _position = position;

    final playing = controller.value.isPlaying;
    _isPlaying = playing;
    if (playing) {
      if (_disposed) return;
      setState(() {
        _progress = position!.inMilliseconds.ceilToDouble() /
            duration.inMilliseconds.ceilToDouble();
      });
      return;
    } else {
      if (_disposed) return;
      _isPlaying = playing;
      setState(() {});
    }
  }

  indexChange(int index) {
    initVideo(index);
  }

  initVideo(int index) {
    final controller = VideoPlayerController.network(videos[index].url);
    final old = _controller;
    if (old != null) {
      old.removeListener(conrtollerUpdate);
      old.pause();
    }
    setState(() {});
    _controller = controller;
    _controller?.initialize().then((_) {
      old?.dispose();
      _progress = 0;
      currentIndex = index;
      _controller?.addListener(conrtollerUpdate);
      _controller?.play();
      setState(() {
        _duration = null;
        _position = null;
        _isPlaying = true;
      });
    });
  }

  @override
  void dispose() {
    _disposed = true;
    _controller?.pause();
    _controller?.removeListener(conrtollerUpdate);
    _controller?.dispose();
    _controller = null;
    super.dispose();
  }

  Widget videoPlay(BuildContext context) {
    Widget video = const Center(
      child: Text(
        '正在加载中...',
        style: TextStyle(color: Colors.white),
      ),
    );
    if (_controller != null && _controller!.value.isInitialized) {
      video = VideoPlayer(_controller!);
    }
    return Container(
      color: Colors.black,
      width: MediaQuery.of(context).size.width,
      child: AspectRatio(
        aspectRatio: _controller?.value.aspectRatio ?? 1,
        child: video,
      ),
    );
  }

  showTip(BuildContext context, String text) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Text(
        text,
        style: TextStyle(color: Colors.black),
      ),
      backgroundColor: Colors.white, //设置背景颜色
      duration: const Duration(seconds: 2),
    ));
  }

  void _toggleFullScreen() {
    setState(() {
      if (_isFullScreen) {
        /// 如果是全屏就切换竖屏
        AutoOrientation.portraitAutoMode();

        ///显示状态栏，与底部虚拟操作按钮
        SystemChrome.setEnabledSystemUIOverlays(
            [SystemUiOverlay.top, SystemUiOverlay.bottom]);
      } else {
        AutoOrientation.landscapeAutoMode();

        ///关闭状态栏，与底部虚拟操作按钮
        SystemChrome.setEnabledSystemUIOverlays([]);
      }
    });
  }

  Duration? _duration;
  Duration? _position;
  // ValueNotifier<double> isUpdate = ValueNotifier<double>(0);
  double _progress = 0;

  String convertTwo(int value) {
    return value < 10 ? '0$value' : '$value';
  }

  bool pausePre = true;
  Widget controllerVideo() {
    final noMute = (_controller?.value.volume ?? 0) > 0;

    /// 设置进度条
    final duration = _duration?.inSeconds ?? 0;
    final head = _position?.inSeconds ?? 0;
    // final remained = max(0,duration - head);

    final mins = convertTwo(head ~/ 60);
    final secs = convertTwo(head % 60);

    final minsend = convertTwo(duration ~/ 60);
    final secsend = convertTwo(duration % 60);
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Row(
          children: [
            Text(
              '$mins:$secs',
              style: TextStyle(color: Colors.white),
            ),
            Expanded(
                child: SliderTheme(
              data: SliderTheme.of(context).copyWith(
                  activeTrackColor: Colors.red[700],
                  inactiveTrackColor: Colors.red[100],
                  trackShape: const RoundedRectSliderTrackShape(),
                  trackHeight: 2.0,
                  thumbShape:
                      const RoundSliderThumbShape(enabledThumbRadius: 10),
                  thumbColor: Colors.redAccent,
                  overlayColor: Colors.red.withAlpha(32),
                  overlayShape: RoundSliderOverlayShape(overlayRadius: 20),
                  tickMarkShape: RoundSliderTickMarkShape(),
                  activeTickMarkColor: Colors.red[700],
                  inactiveTickMarkColor: Colors.red[100],
                  valueIndicatorShape: PaddleSliderValueIndicatorShape(),
                  valueIndicatorColor: Colors.redAccent,
                  valueIndicatorTextStyle: TextStyle(color: Colors.white)),
              child: Slider(
                value: max(0, min(_progress * 100, 100)),
                min: 0,
                max: 100,
                divisions: 100,
                label: _position?.toString().split('.')[0],
                onChanged: (value) {
                  setState(() {
                    _progress = value * 0.01;
                  });
                },
                onChangeStart: (value) {
                  pausePre = _controller?.value.isPlaying ?? true;
                  _controller?.pause();
                },
                onChangeEnd: (value) async {
                  final duration = _controller?.value.duration;
                  if (duration != null) {
                    var newVlaue = max(0, min(value, 100)) * 0.01;
                    var millis = (duration.inMilliseconds * newVlaue).toInt();
                    await _controller?.seekTo(Duration(milliseconds: millis));
                    if (pausePre) {
                      _controller?.play();
                    }
                  }
                },
              ),
            )),
            Text(
              '$minsend:$secsend',
              style: TextStyle(color: Colors.white),
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            IconButton(
                onPressed: () {
                  if (noMute) {
                    _controller?.setVolume(0);
                    _noMute = false;
                  } else {
                    _controller?.setVolume(1);
                    _noMute = true;
                  }
                  setState(() {});
                },
                color: Colors.white,
                icon: Icon(noMute ? Icons.volume_up : Icons.volume_off)),
            Expanded(
                child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                IconButton(
                    onPressed: () {
                      final index = currentIndex - 1;
                      if (index >= 0 && videos.length > 0) {
                        initVideo(index);
                      } else {
                        showTip(context, '已经到了最前面了');
                      }
                    },
                    color: Colors.white,
                    icon: const Icon(Icons.fast_rewind)),
                IconButton(
                    onPressed: () {
                      if (_isPlaying) {
                        _controller?.pause();
                        _isPlaying = false;
                      } else {
                        _controller?.play();
                        _isPlaying = true;
                      }
                      setState(() {});
                    },
                    color: Colors.white,
                    icon: Icon(_isPlaying ? Icons.pause : Icons.play_arrow)),
                IconButton(
                    onPressed: () {
                      final index = currentIndex + 1;
                      if (index <= videos.length - 1) {
                        initVideo(index);
                      } else {
                        showTip(context, '已经没有更多了');
                      }
                    },
                    color: Colors.white,
                    icon: const Icon(Icons.fast_forward))
              ],
            )),
            IconButton(
                onPressed: () {
                  // _toggleFullScreen();
                  showTip(context, '暂时不支持全屏');
                },
                color: Colors.white,
                icon: Icon(Icons.aspect_ratio))
          ],
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          Positioned(
              top: 30,
              width: MediaQuery.of(context).size.width,
              child: SafeArea(
                  child: Center(
                child: Text(
                  '${currentIndex + 1}/${videos.length}',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
              ))),
          Center(
            child: videoPlay(context),
          ),
          Positioned(
              width: MediaQuery.of(context).size.width,
              bottom: 100,
              child: controllerVideo()),
          Offstage(
            offstage: _isPlaying,
            child: Center(
                child: InkWell(
                    onTap: () {
                      _controller?.play();
                      _isPlaying = true;
                    },
                    child: Icon(
                      Icons.play_arrow_sharp,
                      color: Colors.white,
                      size: 100,
                    ))),
          )
        ],
      ),
    );
  }
}
